import React,{useEffect,useState,useMemo} from 'react'
import * as XLSX from 'xlsx'
import './guocoin.css'
import { DatePicker,Button,Space, Table, Tag,TableProps,Modal,Form, Input,Select, FormProps  } from 'antd';
import {getorderlist,getadd} from '../../request/index'
const { RangePicker } = DatePicker;
const { Column} = Table;

// 表格的

interface DataType {
  key: string;
  name: string;
  id:number,
  word:string,
  tel:string,
  natural:number,
  state:string,
  type:string,
  date:string,
  price:number
}
// form表单
type FieldType = {
  id?:number;
  date?: string;
  name?: string;
  natural?: string;
  price?: number;
  state?: string;
   tel?: string;
   type?:string,
   word?:string
};

const columns: TableProps<DataType>['columns'] = [
  {
    title: '序号',
    dataIndex: 'id',
    key: 'id', 
  },
  {
    title: '用户名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '店铺名称',
    dataIndex: 'word',
    key: 'word',
  },
  {
    title: '手机号码',
    key: 'tel',
    dataIndex: 'tel',
  
  },
  {
    title: '业务单据',
    key: 'natural',
    dataIndex: 'natural',
  },
  {
    title: '业务类型',
    dataIndex: 'state',
    key: 'state',
  },
   {
    title: '流水类型',
    dataIndex: 'type',
    key: 'type',
  },
   {
    title: '时间',
    dataIndex: 'date',
    key: 'date',
  },
   {
    title: '果币(元)',
    dataIndex: 'price',
    key: 'price',
    render: (text) => <span style={{ color: 'red' }}>{text}</span>
  },
];




const index: React.FC = () => {
const [search, setSearch] = useState<string>('');
const [tabdata,settabdata]=useState([])
 const [isModalOpen, setIsModalOpen] = useState(false);
 const [form] = Form.useForm();


  // 下拉框的
const handleChange = (value: string) => {
  console.log(`selected ${value}`);
};

  // 定义获取订单列表的函数
  const fetchOrderList = async () => {
    try {
      const res = await getorderlist(); // 调用 API
      console.log('果币数据', res);
      settabdata(res.data.orderList); // 更新状态
    } catch (error) {
      console.error('获取订单列表时出错:', error);
    }
  };

useEffect(()=>{
fetchOrderList();
},[])



  // 导出 Excel 的函数
  const exportToExcel = () => {
    const ws = XLSX.utils.json_to_sheet(tabdata); // 将 JSON 数据转换为工作表
    const wb = XLSX.utils.book_new(); // 创建一个新的工作簿
    XLSX.utils.book_append_sheet(wb, ws, '果币数据'); // 将工作表添加到工作簿
    XLSX.writeFile(wb, '果币数据.xlsx'); // 导出 Excel 文件
  };



// 弹窗
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    form.submit()
    setIsModalOpen(false);
     fetchOrderList();
   

  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

// 表单获取
const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
  console.log('Success:', values);
  getadd(values).then(res=>{
    console.log('res',res);
  //   let newdata=[...tabdata]
  //       values.id= +new Date()
  //     values.natural= +new Date()
  //  newdata.unshift(values)
  //  settabdata(newdata)
 

  })
};

  const filterTableData = useMemo(() => {
    if (!search) return tabdata;

    const query = search.toLowerCase(); // 转为小写以便于比较
    return tabdata.filter(item => item.tel.toLowerCase().includes(query));
    
  }, [search, tabdata]);

  return (
    <div className='guocoinbox'>
      <div className='guo_hed'>
        <div className='hed_hd'>果币</div>
        <div className='hed_ctr'>
        <p>
              <Select
      defaultValue="业务类型"
      style={{ width: 120 }}
      onChange={handleChange}
      options={[
        { value: 'jack', label: '充值业务' },
        { value: 'lucy', label: '退款业务' },
        { value: 'Yiminghe', label: '客服业务' },
        { value: 'disabled', label: '普通业务'},
      ]}
    />
        </p>
        <p>店铺名称：<Input placeholder="请输入店铺名称" style={{width:'200px'}}/></p>
        <p>手机号:<Input placeholder="请输入手机号码" style={{width:'200px'}} value={search}  onChange={(e) => setSearch(e.target.value)}/></p>
        </div>

        <div className='hed_bom'>
          <p>日期查询: <RangePicker /></p>
          <p>
            <Button type="primary">查询</Button>
            &emsp;
            <Button onClick={exportToExcel}>导出</Button>
          </p>
        </div>

      </div>

       <div className='guo_tab'>
          <Button type="primary" onClick={showModal}>充值</Button>
        <Table<DataType> columns={columns} dataSource={filterTableData}/>
          {/* 弹窗 */}
         <Modal title="果币充值" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} cancelText='取消' okText='确认充值'>

            <Form
    name="basic"
    labelCol={{ span: 8 }}
    wrapperCol={{ span: 16 }}
    style={{ maxWidth: 600 }}
      onFinish={onFinish}
    initialValues={{ remember: true }}
    autoComplete="off"
    form={form}
  >


    <Form.Item<FieldType>
      label="用户名"
      name="name"
    >
      <Input />
    </Form.Item>

      
    <Form.Item<FieldType>
      label="店铺名称"
      name="word"
    >
      <Input />
    </Form.Item>

      
    <Form.Item<FieldType>
      label="手机号码"
      name="tel"
    >
      <Input />
    </Form.Item>

      


       <Form.Item<FieldType>
      label="业务类型"
      name="state"
    >
      <Input />
    </Form.Item>

       <Form.Item<FieldType>
      label="流水类型"
      name="type"
    >
      <Input />
    </Form.Item>

       <Form.Item<FieldType>
      label="时间"
      name="date"
    >
      <Input />
    </Form.Item>

       <Form.Item<FieldType>
      label="充值金额"
      name="price"
    >
      <Input />
    </Form.Item>

  </Form>


      </Modal>
       </div>
    </div>
  )
}

export default index
